# 进程是程序在操作系统里的一次执行过程，是系统进行资源分配和调度的基本单位。每个进程都有自己独立的内存空间、系统资源以及数据栈等。
import multiprocessing


def worker(num):
    """进程要执行的任务"""
    print(f'Worker {num} started')
    # 模拟一些工作
    for _ in range(1000000):
        pass
    print(f'Worker {num} finished')


if __name__ == '__main__':
    processes = []
    # 创建 3 个进程
    for i in range(3):
        p = multiprocessing.Process(target=worker, args=(i,))
        processes.append(p)
        p.start()

    # 等待所有进程完成
    for p in processes:
        p.join()

    print('All processes finished')

# 线程是进程中的一个执行单元，是 CPU 调度和分派的基本单位。一个进程可以包含多个线程，这些线程共享进程的内存空间和系统资源。
import threading


def worker(num):
    """线程要执行的任务"""
    print(f'Thread {num} started')
    # 模拟一些工作
    for _ in range(1000000):
        pass
    print(f'Thread {num} finished')


if __name__ == '__main__':
    threads = []
    # 创建 3 个线程
    for i in range(3):
        t = threading.Thread(target=worker, args=(i,))
        threads.append(t)
        t.start()

    # 等待所有线程完成
    for t in threads:
        t.join()

    print('All threads finished')

# 在处理 I/O 密集型任务时，可优先考虑使用线程；而处理 CPU 密集型任务时，则优先考虑使用进程。


# # import keyword
# #
# # print(keyword.kwlist)
# import time
# import asyncio
# import aiohttp
#
# async def fun1():
# 	await asyncio.sleep(5)
# 	return "fun1_result"
#
#
# async def fun2():
# 	await asyncio.sleep(5)
# 	return "fun2_result"
#
#
# async def main():
# 	task1 = asyncio.create_task(fun1())
# 	task2 = asyncio.create_task(fun2())
#
# 	r1 = await task1
# 	r2 = await task2
# 	print(r1, r2)
# asyncio.run(main())
#
# print("the end")
#




# async def fun1():
# 	async with aiohttp.ClientSession() as session:
# 		async with session.get('http://httpbin.org/get?age=10') as response:
# 			return await response.json()
#
#
# async def fun2():
# 	async with aiohttp.ClientSession() as session:
# 		async with session.get('http://httpbin.org/get?age=20') as response:
# 			return await response.json()
#
# async def main():
#
# 	results = await asyncio.gather(*[asyncio.create_task(fun1()), asyncio.create_task(fun2())])
# 	for r in results:
# 		print(r)
#
# asyncio.run(main())
#
# print("the end")
#






# async def fun(url):
# 	async with aiohttp.ClientSession() as session:
# 		async with session.get(url) as response:
# 			return await response.json()
#
# async def main():
# 	urls = [f"http://httpbin.org/get?age={i}" for i in range(100)]
# 	results = await asyncio.gather(*[ asyncio.create_task(fun(url))    for url in urls ])
# 	for r in results:
# 		print(r)
#
# asyncio.run(main())
#
# print("the end")








